<?php

namespace App\Http\Controllers;

use App\Constants\ResponseCodeConstant;
use App\Http\Requests\ResourceCategoryCreateRequest;
use App\Services\AdminResourceCategoryService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * 后台资源管理
 * Class AdminUserController
 * @package App\Http\Controllers
 */
class AdminResourceCategoryController extends BaseController
{
    /**
     * 查询所有后台资源分类
     * @return JsonResponse|mixed|object
     */
    public function listAll()
    {
        $result = AdminResourceCategoryService::getInstance()->listAll();
        if ($result) {
            return $this->success($result);
        }
        return $this->fail(ResponseCodeConstant::SEARCH_FAILED,'资源信息分类查询失败');
    }

    /**
     * 添加后台分类资源
     * @param ResourceCategoryCreateRequest $request
     * @return JsonResponse|mixed|object
     */
    public function create(ResourceCategoryCreateRequest $request)
    {
        $name = $request->post('name');
        $sort = $request->post('sort',0);
        $data = [
          'name' => $name,
          'sort' => $sort
        ];
        $result = AdminResourceCategoryService::getInstance()->create($data);
        if ($result) {
            return $this->success();
        }
        return $this->fail(ResponseCodeConstant::CREATE_FAILED,'资源信息分类创建失败');
    }

    /**
     * 修改后台资源分类
     * @param Request $request
     * @return JsonResponse|mixed|object
     */
    public function update(Request $request)
    {
        $id = $request->route('id');
        $data = [];
        if ($request->has('name')) {
            $data['name'] = $request->post('name');
        }
        if ($request->has('sort')) {
            $data['sort'] = $request->post('sort');
        }
        $result = false;
        if ($data) {
            $result = AdminResourceCategoryService::getInstance()->updateById($data,$id);
        }
        if ($result) {
            return $this->success();
        }
        return $this->fail(ResponseCodeConstant::UPDATE_FAILED,'资源信息分类修改失败');
    }

    /**
     * 根据ID删除资源分类
     * @param Request $request
     * @return JsonResponse|mixed|object
     */
    public function delete(Request $request)
    {
        $id = $request->route('id');
        $result = AdminResourceCategoryService::getInstance()->deleteById($id);
        if ($result) {
            return $this->success();
        }
        return $this->fail(ResponseCodeConstant::DELETE_FAILED,'资源信息分类删除失败');
    }

}
